package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.pojo.Supplier;
import com.bdqn.service.SupplierService;
import com.bdqn.utils.Constants;
import com.bdqn.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/supplier")
public class SupplierController {
    // 日志
    private Logger logger = Logger.getLogger(SysUserController.class);

    @Resource
    private SupplierService supplierService;
    @GetMapping("/list")
    public String toList(Model model, String querySupName, String querySupCode, @RequestParam(defaultValue = "1")Integer pageIndex){
        List<Supplier> supplierList = null;
        try{
            //设置页面容量
            int pageSize = Constants.pageSize;
            //总数量
            int totalCount = supplierService.getCount();
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex); // 设置当前页数
            pages.setPageSize(pageSize);       // 设置一页显示数据量
            pages.setTotalCount(totalCount);   // 设置总数据量
            int totalPageCount = pages.getTotalPageCount();

            //控制首页和尾页
            if (pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }

            supplierList=supplierService.queryPageByRealNameAndRoleId((pageIndex-1)*pageSize,pageSize,querySupCode,querySupName);

            model.addAttribute("supplierList",supplierList);  // 供货商信息

            model.addAttribute("totalCount",pages.getTotalCount()); // 分页信息
            model.addAttribute("currentPageNo",pages.getPageNo());
            model.addAttribute("totalPageCount",pages.getTotalPageCount());

            model.addAttribute("querySupName",querySupName); // 查询条件回显
            model.addAttribute("querySupCode",querySupCode);

        }catch (Exception e){
            e.printStackTrace();
        }
        return "/supplier/list";
    }

    @PostMapping("/add")
    public String add(String supCode, String supName, String supContact, String supPhone, String supAddress, String supFax, String supDesc, @RequestParam("attachs") MultipartFile companyLicPic, @RequestParam("attachs2") MultipartFile orgCodePic, HttpServletRequest request, HttpSession session){
        // 文件上传到服务器的真实位置
        String uploadPath = session.getServletContext().getRealPath(Constants.UPLOAD_PATH);

        Map<String,String> msg = new HashMap<>();
        Supplier supplier = new Supplier();

        // 上传企业营业执照
        if (companyLicPic != null){
            String companyPath = multipartFileUpload(uploadPath,companyLicPic,msg);
            if (companyPath == null){
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("uploadFileError2",uploadFileError);
                request.removeAttribute("uploadFileError"); // 临时使用，使用后移除信息
                return "/supplier/add";
            }
            supplier.setCompanyLicPic(companyPath);
        }
        if (orgCodePic != null){
            String orgCodePath = multipartFileUpload(uploadPath,orgCodePic,msg);
            if (orgCodePath == null){
                String uploadFileError = msg.get("uploadFileError");
                request.setAttribute("uploadOcError",uploadFileError);
                request.removeAttribute("uploadFileError"); // 临时使用，使用后移除信息
                return "/supplier/add";
            }
            supplier.setOrgCodePic(orgCodePath);
        }

        supplier.setSupCode(supCode);
        supplier.setSupName(supName);
        supplier.setSupContact(supContact);
        supplier.setSupPhone(supPhone);
        supplier.setSupAddress(supAddress);
        supplier.setSupFax(supFax);
        supplier.setSupDesc(supDesc);
        // 调用方法把数据添加到数据库中
        int add = supplierService.add(supplier);

        // 跳转到供货商信息页面
        return "redirect:/supplier/list";
    }

    public synchronized String multipartFileUpload(String uploadPath, MultipartFile multipartFile, Map<String,String> msg) {
        String uploadFilePath = null; // 文件上传地址，返回null表示文件上传失败

        // 定义文件存放目录
        logger.debug("上传文件路径：" + uploadPath);

        if (!multipartFile.isEmpty()) {
            String originalFile = multipartFile.getOriginalFilename();
            logger.debug("原文件名称为：" + originalFile);
            String prefix = FilenameUtils.getExtension(originalFile);
            logger.debug("原文件后缀为：" + prefix);
            long fileSize = multipartFile.getSize();
            logger.debug("上传文件大小：" + fileSize);

            if (fileSize > Constants.MAX_FILE_SIZE) {  // 上传文件大小不能超过500KB
                msg.put("uploadFileError", "*上传文件大小不得超过5MB");
                return uploadFilePath;
            }
            // 判断文件格式
            if (!(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg"))) {
                msg.put("uploadFileError", "*上传文件格式只能是jpg,jpeg,png,pneg");
                return uploadFilePath;
            }

            // 确认文件名称
            String fileName = System.nanoTime() + RandomUtils.nextInt(0, 1000) + "_Personal." + prefix;
            logger.debug("新生成的文件名为：" + fileName);

            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }

            // 保存文件
            try {
                // 储存物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                msg.put("uploadFileError", "文件上传失败");
                return uploadFilePath;
            }
            // 文件上传成功就可以拿到地址
            uploadFilePath = "/" + Constants.UPLOAD_PATH + "/" + fileName;
        }
        // 返回文件上传成功的地址，失败返回null,并且将失败信息记录到map中
        return uploadFilePath;
    }

    // 跳转到修改页面
    @GetMapping("/toUpdate/{supId}")
    public String toUpdate(Model model,@PathVariable Integer supId){
        Supplier supplier = supplierService.getSupplier(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }

    @PostMapping("/update")
    public String update(HttpServletResponse response, Integer id, String supCode, String supName, String supPhone, String supContact, String supAddress, String supFax, String supDesc) throws IOException {
        Supplier supplier = new Supplier();
        supplier.setId(id);
        supplier.setSupCode(supCode);
        supplier.setSupName(supName);
        supplier.setSupPhone(supPhone);
        supplier.setSupContact(supContact);
        supplier.setSupAddress(supAddress);
        supplier.setSupFax(supFax);
        supplier.setSupDesc(supDesc);

        int upd = supplierService.upd(supplier);

        return "supplier/list";
    }

    @ResponseBody  // 让返回的内容原样输出到页面（通常用于ajax处理）
    @GetMapping("/del/{supId}")
    public String del(@PathVariable Integer supId){
        Map<String,String> map = new HashMap<>();
        int del = supplierService.del(supId);

        if (del == 1){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }

        return JSON.toJSONString(map);
    }
    @RequestMapping("/view/{supId}")
    public String getView(@PathVariable Integer supId,Model model){
        Supplier supplier = supplierService.getSupplier(supId);
        model.addAttribute("supplier",supplier);
        return "/supplier/view";
    }

    @GetMapping("/add")
    public String toAdd(){ return "/supplier/add"; }
}
